package com.yalu.util;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.yalu.dao.data.StoresDao;
import com.yalu.entity.data.Stores;
import com.yalu.entity.data.StoresProperties;
import com.yalu.entity.data.Taskcost;
import com.yalu.entity.data.TaskcostKey;

public class TaskcostExcelImportUtil extends BaseExcelImportUtil{
	private List<List<String>> str = null;
	private StoresDao stroesDao = (StoresDao) SpringUtil
	.getBean("storesDaoImpl");
	private static final String TITLE = "店铺ID,店铺名称,时间,销售任务合计,任务成本合计";
	Map<Integer, Stores> storesMap = new HashMap<Integer, Stores>();
	private static int COLUMN_COUNT = 4;
	private static int MAX_ATTRIBUTE_ID = 7;
	public TaskcostExcelImportUtil() {
		List<Stores> storesList = stroesDao.getAll();
		for (Stores stores : storesList) {
			storesMap.put(stores.getNo(), stores);
		}
	}

	public List<String> importExcel(String excelFile) {
		try {
			List<List<String>> array = readExcelReturnArray(excelFile);
			return validate(array);
		} catch (Exception e) {
			e.printStackTrace();
			return errMsg;
		}

	}

	private List<String> validate(List<List<String>> array) {
		for (int rowIndex = 0; rowIndex < array.size(); rowIndex++) {
			List<String> row = array.get(rowIndex);
				if (rowIndex == 0) {
					String msg = validateTitle(row);
					if (msg != null) {
						errMsg.add(msg);
					}
				} else {
					String msg = validateData(rowIndex, row);
					if (msg != null) {
						errMsg.add(msg);
					}
				}
		}
		int size  = dataList.size();
		//从两头轮询开始比较
		for(int i = 0;i<size;i++){
			Taskcost entity = (Taskcost)dataList.get(i);
			for (int j = size-1; j > i; j--) {
				if(i<j){//保证不是同一行
					Taskcost entityTmp = (Taskcost)dataList.get(j);
					if(entity.getTaskcostKey().equals(entityTmp.getTaskcostKey())){
						String msg = "【时间】栏第【"+(i+1)+"】笔与第【"+(j+1)+"】笔数据重复";
						errMsg.add(msg);
					}
				}
			}
		}
		return errMsg;
	}

	/**
	 * @Description: 数据格式校验
	 * @param rowIndex
	 * @param row
	 * @return
	 * @date 2013-10-29 上午12:21:12
	 * @author zch
	 */
	private String validateData(int rowIndex, List<String> row) {
		Taskcost entity = new Taskcost();
		TaskcostKey taskcostKey = new TaskcostKey();
		entity.setTaskcostKey(taskcostKey);
		String msg = "";
		String value = "";
		
		for (int columnIndex = 0; columnIndex < COLUMN_COUNT; columnIndex++) {
			value = row.get(columnIndex);
			switch (columnIndex) {
			case 0:
				try {
					Double doubleValue = Double.parseDouble(value);
					if(doubleValue.intValue()==doubleValue){
						entity.getTaskcostKey().setStore_id(doubleValue.intValue());
					}else{
						msg = "【店铺ID】栏第【" + rowIndex + "】笔数据格式不正确";
						return msg;
					}
				} catch (Exception e) {
					msg = "【店铺ID】栏第【" + rowIndex + "】笔数据格式不正确";
					return msg;
				}
				break;
			case 1:
				Stores stores = storesMap.get(entity.getTaskcostKey().getStore_id());
				if(stores!=null&&!stores.getName().equals(value)){
					msg = "【店铺名称】栏第【" + rowIndex + "】笔，店铺名称与平台店铺属性参数不符";
					return msg;
				}else{
					entity.getTaskcostKey().setStore_name(value);
				}
				break;
			case 2:
				if(value.length()==6||value.length()==8){
					try {
						SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
						formatter.setLenient(false);
						formatter.format(formatter.parse(value));
						entity.getTaskcostKey().setData_date(value);
					} catch (Exception e) {
						try {
						SimpleDateFormat formatter = new SimpleDateFormat("yyyyMM");
						formatter.setLenient(false);
						formatter.format(formatter.parse(value));
						entity.getTaskcostKey().setData_date(value);
						} catch (Exception ex) {
							msg = "【时间】栏第【" + rowIndex + "】笔数据格式不正确";
							return msg;
						}
					}
				}else{
					msg = "【时间】栏第【" + rowIndex + "】笔数据格式不正确,日期格式应为6码（yyyymm）或8码（yyyymmdd）";
					return msg;
				}
				break;
			case 3:
				try {
					Double doubleValue = Double.parseDouble(value);
					if(doubleValue.intValue()==doubleValue){
						entity.setSelltasks(doubleValue.intValue());
					}else{
						msg = "【销售任务合计】栏第【" + rowIndex + "】笔数据格式不正确";
						return msg;
					}
				} catch (Exception e) {
					if(!value.equals("")){
						msg = "【销售任务合计】栏第【" + rowIndex + "】笔数据格式不正确";
						return msg;
					}else{
						entity.setSelltasks(0);
					}
				}
				break;
			case 4:
				try {
					Double doubleValue = Double.parseDouble(value);
					if(doubleValue.intValue()==doubleValue){
						entity.setTaskcosts(doubleValue.intValue());
					}else{
						msg = "【任务成本合计】栏第【" + rowIndex + "】笔数据格式不正确";
						return msg;
					}
				} catch (Exception e) {
					if(!value.equals("")){
						msg = "【任务成本合计】栏第【" + rowIndex + "】笔数据格式不正确";
						return msg;
					}else{
						entity.setTaskcosts(0);
					}
				}
				break;}
		}
		dataList.add(entity);
		return null;
	}

	/**
	 * @Description: 校验标题行
	 * @param row
	 * @return
	 * @date 2013-10-29 上午12:19:39
	 * @author zch
	 */
	private String validateTitle(List<String> row) {
		String msg = "";
		String title = "";
		for (int index = 0; index < COLUMN_COUNT; index++) {
			if(index!=COLUMN_COUNT-1){
				title = title+row.get(index) + ",";
			}else{
				title = title+row.get(index) ;
			}
			
		}
		
		if (!TITLE.startsWith(title)&&!TITLE.equals(title)) {
			msg = "首行标题依次应为--" + TITLE;
			return msg;
		} else {
			return null;
		}
	}
	
	public List<List<String>> readExcelReturnArray(String excelFile)
			throws Exception {
		List<List<String>> array = new ArrayList<List<String>>();
		InputStream stream = null;
		try {
			stream = new FileInputStream(excelFile);
			XSSFWorkbook myWorkBook = new XSSFWorkbook(stream);
			XSSFSheet mySheet = myWorkBook.getSheetAt(0);
			Iterator<Row> rowIter = mySheet.rowIterator();
			String cellValue = "";
			int rowIndex = 0;
			while (rowIter.hasNext()) {
				XSSFRow myRow = (XSSFRow) rowIter.next();
				if(myRow==null){
					continue;
				}
//				Iterator<Cell> cellIter = myRow.cellIterator();
				List<String> rowArr = new ArrayList<String>();
				
				for (int cellnum = 0; cellnum <= COLUMN_COUNT; cellnum++) {
					cellValue = "";
					XSSFCell myCell = (XSSFCell) myRow.getCell(cellnum);
					if(myCell==null){
						rowArr.add(cellValue.trim());
						continue;
					}
//					int columnIndex = myCell.getColumnIndex();
					
					switch (myCell.getCellType()) {
					case XSSFCell.CELL_TYPE_NUMERIC:
						Double numCellValue = myCell.getNumericCellValue();
						if (DateUtil.isCellDateFormatted(myCell)) {
							Date t = myCell.getDateCellValue();
							SimpleDateFormat format = new SimpleDateFormat(
									"yyyyMMdd");
							cellValue = format.format(t);
						} else {
							cellValue = numCellValue.intValue() + "";//日期特殊处理
						}
						break;
					case XSSFCell.CELL_TYPE_STRING:
						String strCellString = myCell.getStringCellValue();
						cellValue = strCellString;
						break;
					case XSSFCell.CELL_TYPE_BLANK:
						break;
					}
					rowArr.add(cellValue.trim());
				}
				for (int columnIndex = COLUMN_COUNT; columnIndex > rowArr.size();) {
					rowArr.add("");
				}
				//不加入空行数据
				for(String str : rowArr){
					if(!str.equals("")){
						array.add(rowArr);
						break;
					}
				}
				rowIndex++;
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw e;
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (stream != null) {
				try {
					stream.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}

		return array;
	}

	public List<List<String>> getStr() {
		return str;
	}

	public void setStr(List<List<String>> str) {
		this.str = str;
	}
}
